<style lang="less">
  .form-input-w {
    width: 50%;
  }
  //头像上传
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #20a0ff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
<template>
  <section>
    <!--工具条-->
    <search-bar more-display>
      <el-row>
        <el-col :span="8">
          <el-form-item label="客户姓名">
            <el-input  v-model="searchBarName" placeholder="客户姓名"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账户名称">
            <el-input  v-model="searchBarAccount" placeholder="账户名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户手机">
            <el-input  v-model="searchBarPhone" placeholder="客户手机"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="所属企业">
            <el-input  v-model="searchBarEnterprise" placeholder="所属企业"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="账户状态">
            <el-select  v-model="accountStatusvalue" placeholder="请选择账户状态（是否启用）">
              <el-option v-for="item in $store.getters.INDICATOR"
                         :key="item.dictVal"
                         :label="item.cnDictValname"
                         :value="item.dictVal"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="注册日期">
            <el-date-picker
              v-model="searchBarCreateDate3"
              type="daterange"
              align="right"
              placeholder="选择日期范围"
              :picker-options="pickerOptions2">
            </el-date-picker>

          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户等级">
            <el-select v-model="searchBarPersonalLevel" placeholder="请选择">
              <el-option
              v-for="item in $store.getters.MEMBERSHIP_GRADE"
              :label="item.cnDictValname"
              :key="item.dictVal"
              :value="item.dictVal"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
    </search-bar>
    <!-- 操作 -->
    <el-col :span="24" style="margin-bottom: 10px">
      <el-button type="primary" @click="handleAdd" v-if="btns.indexOf('add_btn')>-1">新增</el-button>
      <el-button type="success" @click="batchStart" v-if="btns.indexOf('batchStart_btn')>-1">启用</el-button>
      <el-button type="warning" @click="batchStop" v-if="btns.indexOf('batchStop_btn')>-1">停用</el-button>
      <el-button type="danger" @click="batchDel" v-if="btns.indexOf('batchDelet_btn')>-1">删除</el-button>
      <el-button type="primary" @click="resetCondition" style="float: right">重置</el-button>
      <el-button type="primary" v-on:click="searchMembers" style="float: right">查询</el-button>
    </el-col>
    <!--列表-->
    <el-table :data="tableData" highlight-current-row border @sort-change="sortChange" max-height="650"
              @selection-change="selsChange" v-loading="listLoading" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column prop="statusName" width="120" label="账户状态" >
      </el-table-column>
      <el-table-column prop="realName" label="客户姓名" width="150" >
      </el-table-column>
      <el-table-column prop="personalLevelName" label="客户等级" width="150" >
      </el-table-column>
      <el-table-column prop="account" label="账户名称" width="200" >
      </el-table-column>
      <el-table-column prop="phone" label="客户手机" width="180" >
      </el-table-column>
      <el-table-column prop="enterprise" label="所属企业" width="200" >
      </el-table-column>
      <el-table-column prop="partnerName" label="所属合伙人"   >
      </el-table-column>
      <el-table-column prop="createDate" label="注册日期" width="180" >
      </el-table-column>
      <el-table-column label="操作" width="400">
        <template slot-scope="scope">
          <el-button  type="primary" @click="idManage(scope.$index, scope.row)"
          v-if="btns.indexOf('accountManage_btn')>-1" style="margin-left: 5px">账户管理</el-button>
          <el-button  type="primary" @click="resetPassword(scope.$index, scope.row)"
                      v-if="btns.indexOf('resetPassword_btn')>-1" style="margin-left: 5px">重置密码
          </el-button>
          <el-button  type="primary" @click="getEditBYId(scope.$index, scope.row)"
                      v-if="btns.indexOf('edit_btn')>-1" style="margin-left: 5px">编辑 </el-button>
          <el-button type="success" v-if="scope.row.status===111002002 && btns.indexOf('start_btn')>-1"  style="margin-left: 5px"
                     @click="handleStart(scope.$index, scope.row)">启用
          </el-button>
          <el-button type="warning" v-if="scope.row.status===111002001&& btns.indexOf('stop_btn')>-1" style="margin-left: 5px"
                     @click="handleStop(scope.$index, scope.row)">停用
          </el-button>
          <el-button type="danger"  @click="handleDel(scope.$index, scope.row)"  v-if="btns.indexOf('delet_btn')>-1"  style="margin-left: 5px">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total,sizes,prev, pager, next, jumper"
        :total="total" style="float: right">
      </el-pagination>
    </el-col>
    <!--新增/修改 弹窗 -->
    <el-dialog :title="dialogTitle" size="tiny" :visible.sync="myFormVisible" :close-on-click-modal="false">
      <el-form :model="myForm" :rules="rules" label-width="120px" ref="myForm">
        <el-form-item label="账户名称" prop="account">
          <el-input v-model="myForm.account" auto-complete="off" placeholder="请输入账户名称" class="form-input-w"></el-input>
        </el-form-item>
        <el-form-item label="客户姓名" prop="realName">
          <el-input v-model="myForm.realName" auto-complete="off" placeholder="请输入真实姓名" class="form-input-w"></el-input>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="mySex">
            <el-radio class="radio" :label="107002001">男</el-radio>
            <el-radio class="radio" :label="107002002">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="客户手机" prop="phone">
          <el-input v-model="myForm.phone" auto-complete="off" placeholder="请输入手机号码" class="form-input-w"></el-input>
        </el-form-item>
        <el-form-item label="电话号码" prop="telephone">
          <el-input v-model="myForm.telephone" auto-complete="off" placeholder="请输入电话号码" class="form-input-w"></el-input>
        </el-form-item>
        <el-form-item label="邮件" prop="email">
          <el-input v-model="myForm.email" auto-complete="off" placeholder="请输入邮件" class="form-input-w"></el-input>
        </el-form-item>

        <el-form-item label="通信地址">
          <address-select v-model="invoiceAddressSelect" style="width: 50%"></address-select>
          <address-update-warn v-if="myForm.id && invoiceAddressSelect[3] == null" >
          </address-update-warn>
        </el-form-item>

        <el-form-item prop="street">
          <el-input auto-complete="off" v-model="myForm.street" placeholder="详细地址" class="form-input-w"></el-input>
        </el-form-item>

        <el-form-item label="所属企业" prop="enterprise">
          <el-input v-model="myForm.enterprise" auto-complete="off" placeholder="请输入企业名称" class="form-input-w"></el-input>
        </el-form-item>
        <el-form-item label="事业合伙人" prop="partnerName">
          <el-input disabled v-model="myForm.partnerName" auto-complete="off" class="form-input-w"
                    placeholder="事业合伙人名称"></el-input>
        </el-form-item>
        <el-form-item label="合伙人邀请码" prop="partnerInvitationCode">
          <el-input v-model="myForm.partnerInvitationCode" auto-complete="off" class="form-input-w"
                    placeholder="请输入事业和伙人邀请码"></el-input>
          <el-button  type="primary" @click="checkPartner(myForm.partnerInvitationCode)">检测
          </el-button>
        </el-form-item>
        <el-form-item label="上传头像" prop="currentHeadUrl">
          <el-upload
            class="avatar-uploader"
            action="/api/v1.0/admin/meb_users_head_picture_upload"
            :show-file-list="false"
            :on-error="handleAvatarError"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
            <img v-if="oldHeadUrl && myForm.currentHeadUrl"
                 :src="decodeURI(myForm.downloadHead + myForm.currentHeadUrl)" class="avatar">
            <img v-else-if="!oldHeadUrl && tempCurrentHeadUrl" :src="tempCurrentHeadUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type="textarea" :rows="2" placeholder="请输入备注" v-model="myForm.remark" class="form-input-w"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="myFormVisible = false">取消</el-button>
        <el-button type="primary" @click.native="handleSubmit" :loading="submitLoading">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>
<script>
import {
  getMemberUsers,
  getMemberUser,
  saveMemberUser,
  batchStart,
  batchDel,
  resetPasswordById,
  findByInviteCode
} from '../../api/customer/maintain';
import AddressUpdateWarn from '../meb-user/AddressUpdateWarn.vue';
export default {
  components: {
    AddressUpdateWarn
  },
  data () {
    return {

      mySex: 107002001,
      // 账户状态  start
      accountStatusvalue: '', // 显示值
      // 账户状态  end

      // 输入框值  start
      searchBarName: '',
      searchBarAccount: '',
      searchBarPhone: '',
      searchBarEnterprise: '',
      searchBarCreateDate: '',
      searchBarCreateDate2: '',
      searchBarCreateDate3: '',
      searchBarPersonalLevel: '', // 客户等级
      // 输入框值  end

      // 日期控件
      pickerOptions2: {
        shortcuts: [{
          text: '最近一周',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick (picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },

      // 日期控件

      // 新增框--地址  start
      options2: [], // 地址
      o: null,
      props: {
        label: 'name',
        value: 'id',
        children: 'children'
      },
      // 新增框--地址  end
      dialogTitle: '新增',
      condition: {
        name: '',
        number: ''
      },
      sels: [],
      tableData: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      sortProp: null,
      sortOrder: 'ascending',
      listLoading: false,
      myFormVisible: false,
      submitLoading: false,
      // 表单数据
      myForm: {
        'account': null,
        'realName': null,
        'sex': null,
        'phone': null,
        'telephone': null,
        'email': null,
        'personalLocation': null,

        'enterprise': null,
        'partnerName': null,
        'partnerId': null,
        'partnerInvitationCode': null,

        provinceId: '',
        cityId: '',
        countyId: ''
      },
      invoiceAddressSelect: [],
      // 验证规则
      rules: {
        account: [
          {required: true, message: '请输入账户名称', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur'}
        ],
        email: [
          {required: true, message: '请输入邮箱地址', trigger: 'blur'},
          {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur,change'}
        ],
        realName: [
          {required: true, message: '请输入真实姓名', trigger: 'blur'},
          {min: 2, max: 30, message: '长度在 3 到 15 个字符', trigger: 'blur'}
        ],

        phone: [
          {required: true, message: '请输入手机号码', trigger: 'blur'},
          {min: 11, max: 11, message: '请输入11位手机号码', trigger: 'blur'}
        ],

        partnerInvitationCode: [
          {required: true, message: '请输入合伙人邀请码', trigger: 'blur'},
          {min: 6, max: 6, message: '请输入合伙人邀请码', trigger: 'blur'}
        ]
      },
      // 临时显示图片
      oldHeadUrl: true,
      tempCurrentHeadUrl: ''
    };
  },

  methods: {
    // 头像上传
    handleAvatarSuccess (res, file) {
      this.oldHeadUrl = false;
      this.tempCurrentHeadUrl = URL.createObjectURL(file.raw);// 临时
      this.myForm.currentHeadUrl = res.obj;
    },
    handleAvatarError () {
      this.$message.error('上传头像图片失败!');
    },
    beforeAvatarUpload (file) {
      let isJPG = false;
      if (file.type) {
        const fileTypes = 'image/jpeg;image/png;image/bmp;image/tiff;image/wmf';
        isJPG = fileTypes.indexOf(file.type) !== -1;
      }
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG/PNG/BMP/TIFF/WMF 格式!');
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!');
      }
      return isJPG && isLt2M;
    },
    // 打开新增/编辑窗口时清空用于缓存上传图片属性
    resetHeadUploadData () {
      this.oldHeadUrl = true;
      this.tempCurrentHeadUrl = '';
    },
    // 搜索客户列表
    searchMembers () {
      let params = '';
      // 姓名
      if (this.searchBarName !== null && this.searchBarName !== '') {
        params += 'realName?' + this.searchBarName + ' g0;';
      }
      // 账户
      if (this.searchBarAccount !== null && this.searchBarAccount !== '') {
        params += 'account?' + this.searchBarAccount + ' g1;';
      }
      // 手机
      if (this.searchBarPhone !== null && this.searchBarPhone !== '') {
        params += 'phone?' + this.searchBarPhone + ' g2;';
      }

      // 企业
      if (this.searchBarEnterprise !== null && this.searchBarEnterprise !== '') {
        params += 'enterprise?' + this.searchBarEnterprise + ' g3;';
      }

      // 账户状态
      if (this.accountStatusvalue !== null && this.accountStatusvalue !== '') {
        params += 'status=' + this.accountStatusvalue + ' g4;';
      }
      // 注册日期 起 止
      if (this.searchBarCreateDate3.length > 0 && this.searchBarCreateDate3[0] != null && this.searchBarCreateDate3[1] != null) {
        params += 'createDate>=' + this.searchBarCreateDate3[0].toJSON() + ' g5;';
        params += 'createDate<=' + this.searchBarCreateDate3[1].toJSON() + ' g6;';
      }
      // 客户等级
      if (this.searchBarPersonalLevel !== null && this.searchBarPersonalLevel !== '') {
        params += 'personalLevel=' + this.searchBarPersonalLevel + ' g7;';
      }
      params += 'logicStatus=111002002 g10;';
      getMemberUsers({
        page: this.currentPage,
        size: this.pageSize,
        filters: params,
        sorts: (this.sortProp === null ? '' : (this.sortOrder === 'ascending' ? '-' : '+') + this.sortProp)
      }).then((res) => {
        this.tableData = res.data.detailModelList;
        this.currentPage = res.data.currPage;
        this.total = res.data.totalCount;
        this.pageSize = res.data.pageSize;
        this.listLoading = false;
      });
    },
    // 检测是否有该合伙人
    checkPartner (id) {
      if (id === '' || id == null) {
        this.$message.error('请输入邀请码！');
        return;
      }
      ;
      findByInviteCode(id).then((res) => {
        if (res.data.obj !== null) {
          this.myForm.partnerName = res.data.obj.realName;
          this.myForm.partnerId = res.data.obj.id;
        } else {
          this.$message.error('该邀请码不存在！');
        }
      });
    },
    // 打开编辑界面
    getEditBYId (index, row) {
      this.resetHeadUploadData();
      this.dialogTitle = '修改';
      this.resetForm();
      this.myFormVisible = true;
      this.invoiceAddressSelect = [row.provinceId, row.cityId, row.countyId, row.townId];
      this.myForm = Object.assign({}, row);
    },
    // 跳转到账户管理页面
    idManage (index, row) {
      this.$router.push('/customer/CustomerManage/' + row.userId);
    },
    // 删除单条数据操作
    handleDel (index, row) {
      getMemberUser([row.id]).then((res) => {
        if (res.data.obj !== '') {
          if (res.data.obj.status === 111002001) {
            return this.$message.error('该会员已启用，请停用后再删除！');
          }
        }
      });
      let logicStatus = 111002001;
      this.$confirm('确认删除该用户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        batchDel([row.id], logicStatus).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '恭喜删除成功！',
            type: 'success'
          });
          this.searchMembers();
        });
      }).catch(() => {
      });
    },
    // 单 条重置密码
    resetPassword (index, row) {
      this.$confirm('确认重置该用户的初始密码吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        // 后台有默认值
        let password = null;
        resetPasswordById(row.id, password).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '恭喜重置成功！',
            type: 'success'
          });
          this.searchMembers();
        });
      }).catch(() => {
      });
    },
    // 单 条启用
    handleStart (index, row) {
      this.$confirm('确认启用该用户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let status = 111002001;
        batchStart([row.id], status).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '启用成功！',
            type: 'success'
          });
          this.searchMembers();
        });
      }).catch(() => {
      });
    },
    // 单 条停用
    handleStop (index, row) {
      this.$confirm('确认停用该用户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let status = 111002002;
        batchStart([row.id], status).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '停用成功！',
            type: 'success'
          });
          this.searchMembers();
        });
      }).catch(() => {
      });
    },
    // 新增修改数据提交
    handleSubmit () {
      this.myForm.sex = this.mySex;
      // 表单验证
      this.$refs['myForm'].validate((valid) => {
        if (valid) {
          if (this.invoiceAddressSelect && this.invoiceAddressSelect.length > 0) {
            this.myForm.provinceId = this.invoiceAddressSelect[0];
            this.myForm.cityId = this.invoiceAddressSelect[1];
            this.myForm.countyId = this.invoiceAddressSelect[2];
            this.myForm.townId = this.invoiceAddressSelect[3];
          }
          this.submitLoading = true;
          saveMemberUser(this.myForm).then((res) => {
            this.submitLoading = false;
            if (res.data.successFlg === true) {
              this.myFormVisible = false;
              this.searchMembers();
            } else {
              this.$message.error(res.data.errorMsg);
            }
          }).catch(function (error) {
            console.log(error);
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置表单
    resetForm () {
      for (let p in this.myForm) {
        this.myForm[p] = null;
      }
    },
    // 弹出添加窗体
    handleAdd () {
      this.resetHeadUploadData();
      this.dialogTitle = '新增';
      this.resetForm();
      this.myFormVisible = true;
    },
    // 批量启用
    batchStart () {
      let id = this.sels.map(item => item.id);
      if (id === '' || id == null) {
        this.$message.error('请选择数据！');
        return;
      }
      this.$confirm('确认启用该用户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let status = 111002001;
        batchStart(id, status).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '启用成功！',
            type: 'success'
          });
          this.searchMembers();
        });
      }).catch(() => {
      });
    },
    // 批量停用
    batchStop () {
      let id = this.sels.map(item => item.id);
      if (id === '' || id == null) {
        this.$message.error('请选择数据！');
        return;
      }
      this.$confirm('确认停用该用户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        let status = 111002002;
        batchStart(id, status).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '停用成功！',
            type: 'success'
          });
          this.searchMembers();
        });
      }).catch(() => {
      });
    },
    // 批量删除
    batchDel () {
      let id = this.sels.map(item => item.id);
      if (id === '' || id == null) {
        this.$message.error('请选择数据！');
        return;
      }
      //                getMemberUser(row.id).then((res)=>{
      //                    if(res.data.obj !=""){
      //                        if(res.data.obj.status ===111002001){
      //                            return this.$message.error("该会员已启用，请停用后再删除！");
      //                        }
      //                    }
      //                });

      let logicStatus = 111002001;
      this.$confirm('确认删除该用户吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        batchDel(id, logicStatus).then((res) => {
          this.listLoading = false;
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.searchMembers();
        });
      }).catch(() => {
      });
    },
    selsChange (sels) {
      this.sels = sels;
    },
    sortChange (o) {
      this.sortProp = o.prop;
      this.sortOrder = o.order;
      this.searchMembers();
    },
    handleSizeChange (val) {
      this.pageSize = val;
      this.searchMembers();
    },
    handleCurrentChange (val) {
      this.currentPage = val;
      this.searchMembers();
    },
    resetCondition () {
      this.searchBarName = '';
      this.searchBarAccount = '';
      this.searchBarPhone = '';
      this.searchBarEnterprise = '';
      this.accountStatusvalue = '';
      this.searchBarCreateDate = '';
      this.searchBarCreateDate2 = '';
      this.searchBarCreateDate3 = '';
    }
  },
  computed: {
    btns () {
      return this.$store.state.btns[this.$route.path] || [];
    },
    querys () {
      return this.$store.state.querys[this.$route.path + '#default'] || [];
    }
  },
  // 初始化数据
  mounted () {
    this.$store.commit('initDict');
    this.searchMembers();
  }
};
</script>
